package in.rinisoft.tools.sonar.maven.plugin;

import org.apache.maven.execution.MavenSession;
import org.apache.maven.lifecycle.LifecycleExecutor;
import org.apache.maven.project.MavenProject;
import org.sonar.api.utils.SonarException;
import org.sonar.batch.AbstractMavenPluginExecutor;

import java.util.Arrays;

/**
 * Code has been taken from Sonar maven plugin and modified to suit the need
 * where ever needed
 * 
 * @author Neeraj Mittal 
 */
public class PluginExecutor extends AbstractMavenPluginExecutor {

	private LifecycleExecutor lifecycleExecutor;
	private MavenSession mavenSession;

	public PluginExecutor(LifecycleExecutor le, MavenSession mavenSession) {
		this.lifecycleExecutor = le;
		this.mavenSession = mavenSession;
	}

	@Override
	public void concreteExecute(MavenProject pom, String goal) {
		MavenSession projectSession = mavenSession.clone();
		projectSession.setCurrentProject(pom);
		projectSession.setProjects(Arrays.asList(pom));
		projectSession.getRequest().setRecursive(false);
		projectSession.getRequest().setPom(pom.getFile());
		projectSession.getRequest().setGoals(Arrays.asList(goal));
		projectSession.getRequest().setInteractiveMode(false);
		lifecycleExecutor.execute(projectSession);
		if (projectSession.getResult().hasExceptions()) {
			throw new SonarException("Exception during execution of " + goal);
		}
	}

}
